// src/sidepanel/stores/app.ts - Main Application Store
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export interface TabInfo {
  id: number;
  title: string;
  url: string;
  favicon?: string;
}

export interface PageAnalysis {
  title: string;
  url: string;
  headings: string[];
  links: Array<{ text: string; href: string }>;
  images: Array<{ src: string; alt: string }>;
  wordCount: number;
}

export interface AppSettings {
  autoOpenSidePanel: boolean;
  showFloatingButton: boolean;
  debugMode: boolean;
  theme: 'auto' | 'light' | 'dark';
  fontSize: 'small' | 'medium' | 'large';
}

export const useAppStore = defineStore('app', () => {
  // State
  const currentTab = ref<TabInfo | null>(null);
  const allTabs = ref<TabInfo[]>([]);
  const pageAnalysis = ref<PageAnalysis | null>(null);
  const selectedText = ref<string>('');
  const isLoading = ref<boolean>(false);

  const settings = ref<AppSettings>({
    autoOpenSidePanel: false,
    showFloatingButton: true,
    debugMode: false,
    theme: 'auto',
    fontSize: 'medium'
  });

  const recentActivity = ref<Array<{
    id: string;
    type: string;
    message: string;
    timestamp: Date;
    data?: PageAnalysis | TabInfo | Record<string, unknown>;
  }>>([]);

  // Getters
  const tabsCount = computed(() => allTabs.value.length);
  const hasSelectedText = computed(() => selectedText.value.length > 0);
  const isAnalyzed = computed(() => pageAnalysis.value !== null);

  const recentActivitySorted = computed(() =>
    recentActivity.value
      .sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())
      .slice(0, 10) // Keep only latest 10 activities
  );

  // Actions
  const setCurrentTab = (tab: TabInfo) => {
    currentTab.value = tab;
    addActivity('tab_changed', `Switched to tab: ${tab.title}`);
  };

  const setAllTabs = (tabs: TabInfo[]) => {
    allTabs.value = tabs;
  };

  const setPageAnalysis = (analysis: PageAnalysis) => {
    pageAnalysis.value = analysis;
    addActivity('page_analyzed', `Analyzed page: ${analysis.title}`, analysis);
  };

  const setSelectedText = (text: string) => {
    selectedText.value = text;
    if (text) {
      addActivity('text_selected', `Selected text: ${text.substring(0, 50)}...`);
    }
  };

  const updateSettings = (newSettings: Partial<AppSettings>) => {
    Object.assign(settings.value, newSettings);
    addActivity('settings_updated', 'Settings updated');
  };

  const addActivity = (type: string, message: string, data?: PageAnalysis | TabInfo | Record<string, unknown>) => {
    const activity = {
      id: Date.now().toString(),
      type,
      message,
      timestamp: new Date(),
      data
    };

    recentActivity.value.unshift(activity);

    // Keep only latest 50 activities
    if (recentActivity.value.length > 50) {
      recentActivity.value = recentActivity.value.slice(0, 50);
    }
  };

  const clearActivity = () => {
    recentActivity.value = [];
    addActivity('activity_cleared', 'Activity history cleared');
  };

  const setLoading = (loading: boolean) => {
    isLoading.value = loading;
  };

  // Chrome API helpers
  const getCurrentTabInfo = async (): Promise<TabInfo | null> => {
    try {
      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
      if (tab && tab.id) {
        const tabInfo: TabInfo = {
          id: tab.id,
          title: tab.title || 'Untitled',
          url: tab.url || '',
          favicon: tab.favIconUrl
        };
        setCurrentTab(tabInfo);
        return tabInfo;
      }
    } catch (error) {
      console.error('Error getting current tab:', error);
      addActivity('error', 'Failed to get current tab info');
    }
    return null;
  };

  const getAllTabsInfo = async (): Promise<TabInfo[]> => {
    try {
      const tabs = await chrome.tabs.query({});
      const tabsInfo: TabInfo[] = tabs
        .filter(tab => tab.id && tab.title && tab.url)
        .map(tab => ({
          id: tab.id!,
          title: tab.title!,
          url: tab.url!,
          favicon: tab.favIconUrl
        }));

      setAllTabs(tabsInfo);
      return tabsInfo;
    } catch (error) {
      console.error('Error getting all tabs:', error);
      addActivity('error', 'Failed to get tabs info');
      return [];
    }
  };

  const analyzeCurrentPage = async (): Promise<PageAnalysis | null> => {
    if (!currentTab.value?.id) {
      addActivity('error', 'No current tab to analyze');
      return null;
    }

    setLoading(true);
    try {
      const response = await chrome.tabs.sendMessage(currentTab.value.id, {
        type: 'ANALYZE_PAGE'
      });

      if (response) {
        setPageAnalysis(response);
        return response;
      }
    } catch (error) {
      console.error('Error analyzing page:', error);
      addActivity('error', 'Failed to analyze page');
    } finally {
      setLoading(false);
    }
    return null;
  };

  const highlightTextOnPage = async (text: string): Promise<boolean> => {
    if (!currentTab.value?.id) {
      addActivity('error', 'No current tab for highlighting');
      return false;
    }

    try {
      await chrome.tabs.sendMessage(currentTab.value.id, {
        type: 'HIGHLIGHT_TEXT',
        text
      });

      addActivity('text_highlighted', `Highlighted text: ${text}`);
      return true;
    } catch (error) {
      console.error('Error highlighting text:', error);
      addActivity('error', 'Failed to highlight text');
      return false;
    }
  };

  const saveSettings = async (): Promise<boolean> => {
    try {
      await chrome.storage.local.set({
        sidexSettings: settings.value
      });
      addActivity('settings_saved', 'Settings saved to storage');
      return true;
    } catch (error) {
      console.error('Error saving settings:', error);
      addActivity('error', 'Failed to save settings');
      return false;
    }
  };

  const loadSettings = async (): Promise<boolean> => {
    try {
      const result = await chrome.storage.local.get(['sidexSettings']);
      if (result.sidexSettings) {
        updateSettings(result.sidexSettings);
        addActivity('settings_loaded', 'Settings loaded from storage');
        return true;
      }
    } catch (error) {
      console.error('Error loading settings:', error);
      addActivity('error', 'Failed to load settings');
    }
    return false;
  };

  // Initialize store
  const initialize = async () => {
    await loadSettings();
    await getCurrentTabInfo();
    await getAllTabsInfo();
    addActivity('app_initialized', 'SideX application initialized');
  };

  return {
    // State
    currentTab,
    allTabs,
    pageAnalysis,
    selectedText,
    isLoading,
    settings,
    recentActivity,

    // Getters
    tabsCount,
    hasSelectedText,
    isAnalyzed,
    recentActivitySorted,

    // Actions
    setCurrentTab,
    setAllTabs,
    setPageAnalysis,
    setSelectedText,
    updateSettings,
    addActivity,
    clearActivity,
    setLoading,

    // Chrome API helpers
    getCurrentTabInfo,
    getAllTabsInfo,
    analyzeCurrentPage,
    highlightTextOnPage,
    saveSettings,
    loadSettings,
    initialize
  };
});